/*
The MIT License
Copyright (c) 2019 Lehrstuhl Informatik 11 - RWTH Aachen University
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE

This file is part of embeddedRTPS.

Author: i11 - Embedded Software, RWTH Aachen University
*/

#include "rtps/ThreadPool.h"

#include "lwip/tcpip.h"
#include "rtps/entities/StatelessWriter.h"
#include "rtps/entities/StatefulWriter.h"
#include "rtps/utils/Log.h"
#include "rtps/utils/udpUtils.h"

#if THREAD_POOL_VERBOSE && RTPS_GLOBAL_VERBOSE
#define THREAD_POOL_LOG(...)          \
  if (true) {                        \
    printf("[ThreadPool] ");         \
    printf(__VA_ARGS__);              \
    printf("\n");                     \
  }
#else
#define THREAD_POOL_LOG(...) //
#endif

struct ThreadPool *rtps_ThreadPool_Construct(struct ThreadPool *pPool, receiveJumppad_fp receiveCallback, void *callee) {

  struct ThreadPool *pThreadPool;

  if (!pPool) {
    pThreadPool = (struct ThreadPool *)calloc(1, sizeof(struct ThreadPool));
    if (!pThreadPool) {
      THREAD_POOL_LOG("ThreadPool: Failed to malloc.\n");
      return NULL;
    }
    pThreadPool->bDynamicMem = true;
  } else {
    pThreadPool = pPool;
    pThreadPool->bDynamicMem = false;
  }
  pThreadPool->m_running = false;
  pThreadPool->m_receiveJumppad = receiveCallback;
  pThreadPool->m_callee = callee;
 // init and create queues
  pThreadPool->m_queueOutgoing = rtps_ThreadSafeCircularBuffer_init(rtps_ThreadPool_deconsturct_packet);
  if (!pThreadPool->m_queueOutgoing){
  	THREAD_POOL_LOG("ThreadPool: Failed to init Outgoing queue.\n");
    goto fail;
  }
  
  pThreadPool->m_queueIncoming = rtps_ThreadSafeCircularBuffer_init(rtps_ThreadPool_deconsturct_packet);
  if (!pThreadPool->m_queueIncoming){
  	THREAD_POOL_LOG("ThreadPool: Failed to init Incoming queue.\n");
    rtps_ThreadSafeCircularBuffer_deinit(pThreadPool->m_queueOutgoing);
    goto fail;
  }
  err_t inputErr = sys_sem_new(&pThreadPool->m_readerNotificationSem, 0);
  err_t outputErr = sys_sem_new(&pThreadPool->m_writerNotificationSem, 0);
  if (inputErr != ERR_OK || outputErr != ERR_OK) {
    THREAD_POOL_LOG("ThreadPool: Failed to create Semaphores.\n");
	  goto fail;
  }
  THREAD_POOL_LOG("ThreadPool: Create and init pool %p queueout=%p queuein=%p.\n",
                  pThreadPool,pThreadPool->m_queueOutgoing,pThreadPool->m_queueIncoming);
  return pThreadPool;
  fail:
  if (pThreadPool->bDynamicMem)
    free(pThreadPool);
  return NULL;
}

void rtps_ThreadPool_Destruct(struct ThreadPool *pThreadPool) {
  if (!pThreadPool)
    return;
  
  if (pThreadPool->m_running) {
    stopThreads(pThreadPool);
    sys_msleep(500);
  }

  if (sys_sem_valid(&pThreadPool->m_readerNotificationSem)) {
    sys_sem_free(&pThreadPool->m_readerNotificationSem);
  }
  if (sys_sem_valid(&pThreadPool->m_writerNotificationSem)) {
    sys_sem_free(&pThreadPool->m_writerNotificationSem);
  }

  rtps_ThreadSafeCircularBuffer_deinit(pThreadPool->m_queueOutgoing);
  rtps_ThreadSafeCircularBuffer_deinit(pThreadPool->m_queueIncoming);
  if (pThreadPool->bDynamicMem)
    free(pThreadPool);
}

bool startThreads(struct ThreadPool *pThreadPool) {
  if (pThreadPool->m_running) {
    return true;
  }
  if (!sys_sem_valid(&pThreadPool->m_readerNotificationSem) ||
      !sys_sem_valid(&pThreadPool->m_writerNotificationSem)) {
    return false;
  }

  pThreadPool->m_running = true;

  for (int i = 0; i < THREAD_POOL_NUM_WRITERS; i++) {
    // TODO ID, err check, waitOnStop
    pThreadPool->m_writers[i] = sys_thread_new("WriterThread", writerThreadFunction, pThreadPool,
                            THREAD_POOL_WRITER_STACKSIZE,
                            THREAD_POOL_WRITER_PRIO);
  }

  for (int i = 0; i < THREAD_POOL_NUM_READERS; i++) {
    // TODO ID, err check, waitOnStop
    pThreadPool->m_readers[i] = sys_thread_new("ReaderThread", readerThreadFunction, pThreadPool,
                            THREAD_POOL_READER_STACKSIZE,
                            THREAD_POOL_READER_PRIO);
  }
  return true;
}

void stopThreads(struct ThreadPool *pThreadPool) {
  pThreadPool->m_running = false;
  // This should call all the semaphores for each thread once, so they don't
  // stuck before ended.
  for (int i = 0; i < THREAD_POOL_NUM_WRITERS; i++) {
    sys_sem_signal(&pThreadPool->m_writerNotificationSem);
    sys_msleep(10);
  }
  for (int i = 0; i < THREAD_POOL_NUM_READERS; i++)  {
    sys_sem_signal(&pThreadPool->m_readerNotificationSem);
    sys_msleep(10);
  }
  // TODO make sure they have finished. Seems to be sufficient for tests.
  // Not sufficient if threads shall actually be stopped during runtime.
  sys_msleep(10);
}

void clearQueues(struct ThreadPool *pThreadPool) {

  rtps_ThreadSafeCircularBuffer_clear(pThreadPool->m_queueOutgoing);
  rtps_ThreadSafeCircularBuffer_clear(pThreadPool->m_queueIncoming);
}

bool rtps_ThreadPool_addWorkload(struct ThreadPool *pThreadPool, Writer *workload) {
  bool res = rtps_ThreadSafeCircularBuffe_moveElementIntoBuffer(pThreadPool->m_queueOutgoing, workload);
  if (res) {
    sys_sem_signal(&pThreadPool->m_writerNotificationSem);
  }
  return res;
}

bool addNewPacket(struct ThreadPool *pThreadPool, struct rtps_PacketInfo *packet) {
  bool res = rtps_ThreadSafeCircularBuffe_moveElementIntoBuffer(pThreadPool->m_queueIncoming, packet);
  if (res) {
    sys_sem_signal(&pThreadPool->m_readerNotificationSem);
  }
  return res;
}

void writerThreadFunction(void *arg) {
  struct ThreadPool *pool = (struct ThreadPool *)(arg);
  if (!pool) {
    THREAD_POOL_LOG("nullptr passed to writer function\n");
    return;
  }
  doWriterWork(pool);
}

void doWriterWork(struct ThreadPool *pThreadPool) {
  while (pThreadPool->m_running) {
    Writer *workload;
    bool isWorkToDo = rtps_ThreadSafeCircularBuffer_moveFirstInto(pThreadPool->m_queueOutgoing, (void **)&workload);
    if (!isWorkToDo) {
      sys_sem_wait(&pThreadPool->m_writerNotificationSem);
      continue;
    }

    if (workload->m_bstateful)
        rtps_StatefulWriter_progress((struct rtps_StatefulWriter *)workload);
    else
        rtps_StatelessWriter_progress((struct rtps_StatelessWriter *)workload);
  }
}

void rtps_ThreadPool_readCallback(void *args, udp_pcb *target, struct pbuf *pbuf,
                              const ip_addr_t *addr, Ip4Port_t port) {
  struct ThreadPool *pool = (struct ThreadPool *)(args);

  rtps_PacketInfo *packet;
  packet = (rtps_PacketInfo *)calloc(1, sizeof(rtps_PacketInfo));
  if (!packet) {
    THREAD_POOL_LOG("ThreadPool: %s %d calloc faild", __func__,__LINE__);
    return;
  }
  // TODO This is a workaround for chained pbufs caused by hardware limitations,
  // not a general fix
  if (!pbuf->next) {
    struct pbuf *test = pbuf_alloc(PBUF_RAW, pbuf->tot_len, PBUF_POOL);
    pbuf_copy(test, pbuf);
    pbuf_free(pbuf);
    pbuf = test;
  }
  packet->destAddr.addr = 0;
  packet->destPort = target->local_port;
  packet->srcPort = port;
  packet->buffer = rtps_PBufWrapper_Construct(RTPS_PBW_BY_PBUF, pbuf);
  if (!addNewPacket(pool, packet)) {
    rtps_ThreadPool_deconsturct_packet(packet);
    THREAD_POOL_LOG("ThreadPool: dropped packet\n");
  }
  (void)addr;
}

void rtps_ThreadPool_deconsturct_packet(void *args) {
  rtps_PacketInfo *packet = (rtps_PacketInfo *)args;
  if (packet) {
    rtps_PBufWrapper_Destruct(packet->buffer);
    free(packet);
  }
}

void readerThreadFunction(void *arg) {
  struct ThreadPool *pool = (struct ThreadPool *)(arg);
  if (!pool) {
    THREAD_POOL_LOG("nullptr passed to reader function\n");
    return;
  }
  doReaderWork(pool);
}

void doReaderWork(struct ThreadPool *pool) {
  while (pool->m_running) {
    const rtps_PacketInfo *packet;
    bool isWorkToDo = rtps_ThreadSafeCircularBuffer_moveFirstInto(pool->m_queueIncoming, (void **)&packet);
    if (!isWorkToDo) {
      sys_sem_wait(&pool->m_readerNotificationSem);
      continue;
    }

    pool->m_receiveJumppad(pool->m_callee, packet);
    //release packet
    rtps_ThreadPool_deconsturct_packet((void *)packet);
  }
}

#undef THREAD_POOL_VERBOSE
